import cn from 'classnames';
import PropTypes from 'prop-types';
import React, { useEffect, useState } from 'react';
import fetchFer from 'API/fetch';

import { withRouter } from 'react-router';
import Loading from '@kuiper-components/loading';
import Table, { searchStringBuilder } from '@kuiper-components/page-table';
import Select from '@kuiper-components/select';
import Input from '@kuiper-components/input';
import Button from '@kuiper-components/button';

import { Search24 as SearchIcon } from '@carbon/icons-react';

import CopyBoard from '../../../../components/CopyBoard';
import ChartTitle from '../../../../components/ChartTitle';
import { WARN_LEVEL_MAP } from '../../../../../common/constants';
import { datetime } from '../../../../../common/formatter';
import s from './style.module.css';

const { Option } = Select;

function handleTableFilter({ data, filter }) {
	const filterArr = Object.entries(filter);
	const res = data.filter(row => {
		return filterArr.every(([key, val]) => {
			if (key === 'affects') {
				return (
					row[key]?.toLowerCase()?.indexOf(val?.trim()?.toLowerCase()) > -1
				);
			}
			return val === row[key] || val === '';
		});
	});
	return res;
}

function warningStatsBuilder(warning = {}) {
	let text;
	if (warning.ignoredTime) {
		text = '已忽略';
	} else if (warning.isResolved) {
		text = '已修复';
	} else {
		text = '待修复';
	}
	return text;
}
function VulDetails({
	className,
	jobId,
	resultNumbers = [],
	dateRange,
	ignoredWarnIdMap = {},
	detectTime,
	location,
	tableData,
	taskCategory,
	match,
	history,
	getDropdownRef,
	type,
}) {
	const search = new URLSearchParams(location.search);

	const filter = JSON.parse(
		decodeURIComponent(search.get('filter') || '') || '{}'
	);
	const [url, setUrl] = React.useState(filter.effects);

	const routePrefix = match.path
		.replace(':taskCategory?', 'weakness')
		.replace(':jobId', jobId);

	const onFilterChange = filter => {
		const search = searchStringBuilder(location.search, {
			filter: JSON.stringify(filter),
			page: 1,
			sort: '_ID_DESC',
		});
		history.replace(`${routePrefix}?${search}`);
	};
	const [vulnsTemp, setVulnsTemp] = useState([]);
	const getVulnsTemp = async () => {
		const res = await fetchFer(`/api/v2/vulndb/get_vuln_type`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		const data = res.results.vuln_type.map(item => {
			return { label: item, value: item };
		});
		setVulnsTemp(data);
	};
	const handleUrlSearch = () => {
		onFilterChange({ ...filter, affects: url });
	};

	const handleLevelChange = level => {
		onFilterChange({ ...filter, level });
	};

	const handleStatusChange = status => {
		onFilterChange({ ...filter, status });
	};

	const handleUrlChange = val => {
		if (!val) onFilterChange({ ...filter, affects: undefined });
		setUrl(val);
	};

	const handleCategoryChange = category => {
		onFilterChange({ ...filter, category });
	};

	const filterReset = () => {
		const search = searchStringBuilder(location.search, {
			filter: JSON.stringify({}),
			page: 1,
			sort: '_ID_DESC',
		});
		setUrl('');
		history.replace(`${routePrefix}?${search}`);
	};

	const columns = [
		{
			title: '时间',
			dataIndex: 'date',
			key: 'date',
			className: s.date,
			width: 160,
			// eslint-disable-next-line
			render: date => <div className={s.date}>{date}</div>,
		},
		{
			title: '风险地址',
			dataIndex: 'affects',
			key: 'affects',
			width: 256,
			// eslint-disable-next-line
			render: affects => <CopyBoard text={affects} className={s.affect2} />,
		},
		{
			title: '漏洞名称',
			dataIndex: 'title',
			key: 'title',
			width: 80,
			// eslint-disable-next-line react/display-name
			render: title => <div className={s.col}>{title}</div>,
		},
		{
			title: '漏洞类型',
			dataIndex: 'category',
			key: 'category',
			width: 96,
			// eslint-disable-next-line
			render: category => <div className={s.col}>{category}</div>,
		},
		{
			title: '漏洞等级',
			dataIndex: 'level',
			key: 'level',
			width: 80,
			// eslint-disable-next-line
			render: level => <div className={s.col}>{level}</div>,
		},
		{
			title: '漏洞详情',
			dataIndex: 'detailText',
			key: 'detailText',
			className: s.vulDetail,
			// eslint-disable-next-line
			render: detail => <CopyBoard text={detail} className={s.affect} />,
		},
		// {
		// 	title: '状态',
		// 	dataIndex: 'status',
		// 	key: 'status',
		// 	className: s.col,
		// 	width: '4rem',
		// 	// eslint-disable-next-line
		// 	render: status => (
		// 		<div
		// 			className={cn(s.col, {
		// 				[s.highLight]: status === '待修复',
		// 			})}
		// 		>
		// 			{status}
		// 		</div>
		// 	),
		// },
	];
	useEffect(() => {
		getVulnsTemp();
	}, []);
	return (
		<div className={cn(className, s.detail)}>
			<ChartTitle className={s.title}>漏洞详情</ChartTitle>
			<div className={s.filterContainer}>
				<Input
					className={s.input}
					type="search"
					value={url}
					placeholder="请输入漏洞名称"
					onChange={handleUrlChange}
					after={
						<SearchIcon onClick={handleUrlSearch} className={s.searchIcon} />
					}
					onPressEnter={handleUrlSearch}
				/>
				<div className={s.selectContainer}>
					<Select
						className={s.select}
						placeholder="漏洞类型"
						value={filter?.category}
						onChange={handleCategoryChange}
						getPopupContainer={getDropdownRef}
						allowClear
					>
						{vulnsTemp.map(({ value, label }) => {
							return (
								<Option value={value} key={value}>
									{label}
								</Option>
							);
						})}
					</Select>
					<Select
						className={s.select}
						value={filter?.level}
						placeholder="威胁等级"
						onChange={handleLevelChange}
						getPopupContainer={getDropdownRef}
						allowClear
					>
						{Object.entries(WARN_LEVEL_MAP).map(([id, label]) => (
							<Option key={id} value={label}>
								{label}
							</Option>
						))}
					</Select>
					{/* <Select
						className={s.select}
						placeholder="清选择漏洞状态"
						onChange={handleStatusChange}
						value={filter?.status}
						allowClear
						getPopupContainer={getDropdownRef}
					>
						<Option value="已忽略">已忽略</Option>
						<Option value="已修复">已修复</Option>
						<Option value="待修复">待修复</Option>
					</Select> */}

					<Button className={s.btn} onClick={filterReset}>
						重置
					</Button>
				</div>
			</div>
			<Table
				className={cn(s.table, 'tableFormat')}
				type="local"
				routePrefix={routePrefix}
				columns={columns}
				data={tableData}
				onFilter={handleTableFilter}
			/>
		</div>
	);
}

VulDetails.propTypes = {
	className: PropTypes.string,
	jobId: PropTypes.string,
	getDropdownRef: PropTypes.func.isRequired,
	resultNumbers: PropTypes.arrayOf(
		PropTypes.shape({
			warnCount: PropTypes.number,
			highWarnCount: PropTypes.number,
			mediumWarnCount: PropTypes.number,
			lowWarnCount: PropTypes.number,
			datetime: PropTypes.date,
		})
	),
	dateRange: PropTypes.shape({
		startTime: PropTypes.date,
		endTime: PropTypes.date,
	}),
	detectTime: PropTypes.string,
	ignoredWarnIdMap: PropTypes.object,
	location: PropTypes.shape({
		search: PropTypes.string.isRequired,
	}).isRequired,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
		replace: PropTypes.func.isRequired,
	}).isRequired,
	match: PropTypes.shape({
		path: PropTypes.string.isRequired,
	}).isRequired,
};
VulDetails.defaultProps = {
	className: '',
};

export default withRouter(VulDetails);
